


(function(window) {
    /**
     * 将源对象合并到目标对象中去——内部方法
     * src: 源对象
     * to: 目标对象
     * return 目标对象
     * a = {"a": "a"}
     * b = {"b": "b"}
     * extend_(b, a) →
     * {a: "a", b: "b"}
     */
    function extend_(src, to) {
        if(to === undefined) {
            to = {};
        }
        for(var key in src) {
            to[key] = src[key];
        }
        return to;
    }
    /************************************************VanyTable结束************************************************/
    function _createColumn(prop, label, template) {
        if(template) {
            return "<el-table-column prop='" + prop + "' label='" + label + "' show-overflow-tooltip><template scope='scope'>" + template + "</template></el-table-column>";
        } else {
            return "<el-table-column prop='" + prop + "' label='" + label + "' show-overflow-tooltip></el-table-column>";
        }
    }

    function fnToString(fn) {
        return /\*(.*?)\*/g.exec(fn.toString().replace(/\s+/g, " "))[1].trim();
    }

    function _createBtn(type, label, authority) {
        if(_hasFunction(authority)) {
            return '<el-button type = "' + (type || "primary") + '" @click = "' + authority + '" authority = "' + authority + '">' + label + '</el-button>';
        } else {
            return "";
        }
    }

    function _hasFunction(fnName) {
        var fns = sessionStorage.Jurisdiction.split(",");
        for(var i = 0; i < fns.length; i++) {
            if(fnName === fns[i]) {
                return true;
            }
        }
        return false;
    }

    function genid() {
        return Math.floor(Math.random() * (9999 - 1000 + 1) + 1000);
    }

    function _createAllBtns(btns, postion, btnNotes) {
        typeof(btnNotes) == "undefined" ? btnNotes = '': btnNotes = btnNotes;
        var results = "<div class='table-btns-oper";
        if(postion === "right") {
            results += " right'>";
            for(var i = 0; i < btns.length; i++) {
                results += _createBtn(btns[i].type, btns[i].name, btns[i].authority) + "</br></br>";
            }
        } else {
            results += "'>";
            //results = '<el-row :gutter="8"><el-col :span="12"><el-row :gutter="8"><el-col :span="12"><el-input @change="_restore" @keyup.enter.native="search" :on-icon-click="search" v-model="searchValue" placeholder="请输入您要搜索的内容" icon="search"></el-input></el-col></el-row></el-col><el-col :span="12"><el-row type="flex" justify="end">' + results;
            for(var i = 0; i < btns.length; i++) {
                results += _createBtn(btns[i].type, btns[i].name, btns[i].authority);
            }
            //			/results += "</div></el-row></el-col></el-row>";
        }
        results += btnNotes + "</div>";
        return results;
    }

    function _createAllColumn(keys, hasSelection, hasIndex, hasPages, hasScrollPage, zidingyiTop, zidingyiBtn) {
        typeof(zidingyiTop) == "undefined" ? zidingyiTop = '': zidingyiTop = zidingyiTop;
        typeof(zidingyiBtn) == "undefined" ? zidingyiBtn = '': zidingyiBtn = zidingyiBtn;
        var tableString = zidingyiTop;
        if(hasScrollPage) {
            tableString += "<el-table class='vany-table' ref='table' :data='tableData' :height='height' highlight-current-row @row-click='rowClick' @selection-change='selectionChange'>";
        }
        if(hasPages) {
            tableString += "<el-table class='vany-table' ref='table' :data='tableData' highlight-current-row @row-click='rowClick' @selection-change='selectionChange'>";
        }
        if(hasIndex) {
            tableString += '<el-table-column type="index" width="70"></el-table-column>';
        } //序号
        if(hasSelection) {
            tableString += '<el-table-column type="selection"></el-table-column>';
        } //复选框
        for(var i = 0; i < keys.length; i++) {
            tableString += _createColumn(keys[i]["key"], keys[i]["name"], keys[i]["template"]);
        }
        tableString += "</el-table>";
        if(hasPages) {
            tableString += '<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="pageSizes" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>'
        }
        return tableString + zidingyiBtn;
    }

    /**
     * 判断一个可滚动元素是否滚动到了底部
     * e: 元素
     * fn: 滚动到底部需要执行的回调
     * isScrollToBottom(div, function(){})
     */
    function isScrollToBottom(e, fn) {
        // e.srcElement存在兼容性问题，并非标准特性
        // https://developer.mozilla.org/zh-CN/docs/Web/API/Event/target
        // 支持 IE6-8
        var target_ = e.target || e.srcElement,
            // 距离顶部高度
            scrollTop = target_.scrollTop,
            // 滚动区域高度
            scrollHeight = target_.scrollHeight,
            // 文档元素高度
            clientHeight = target_.clientHeight;
        // 文档坐标和视口坐标转换，判断元素滚动到了底部
        if(scrollTop + clientHeight == scrollHeight) {
            if(fn) {
                fn.call();
            }
        }
    }

    /**
     * 函数节流器，在时间间隔内不触发函数（优化）
     * 应用场景：需要反复重复执行的事件，如快速重复点击按钮等等
     * method: 函数 function a(){}
     * throttle(a)
     */
    function throttle(method, context) {
        clearTimeout(method.tId);
        method.tId = setTimeout(function() {
            method.call(context);
        }, 100);
    }

    function VanyMyTable(opts) {
        var tableListData = '';
        var rowsNum = 0;
        var el_ = document.getElementById(opts.el.split("#")[1]),
            tableString = _createAllColumn(opts.keys, opts.selection, opts.index, opts.pages, opts.scrollPage, opts.zidingyiTop, opts.zidingyiBtn),
            btnsString = _createAllBtns(opts.btns, opts.btnPostion, opts.btnNotes);
        if(opts.btnPostion === "right") {
            var row = '<el-row :gutter="20"><el-col :span="18">';
            var input_ = '<el-input @change="_restore" @keyup.enter.native="search" :on-icon-click="search" v-model="searchValue" placeholder="请输入您要搜索的内容" icon="search"></el-input>';
            row = row + input_ + tableString + '</el-col><el-col :span="6">' + btnsString + '</el-col></el-row>';
            if(typeof(opts.zidingyiTop) === 'string') {
                input_ = ''
            }
            el_.innerHTML = row;
        } else if(opts.btnPostion === "bottomLeft") {
            var input_ = '<el-row :gutter="8"><el-col :span="6"><el-input @change="_restore" @keyup.enter.native="search" :on-icon-click="search" v-model="searchValue" placeholder="请输入您要搜索的内容" icon="search"></el-input></el-col></el-row>';
            if(typeof(opts.zidingyiTop) === 'string') {
                input_ = ''
            }
            el_.innerHTML = input_ + tableString + btnsString;
        } else {
            var row = '<el-row :gutter="8"><el-col :span="12"><el-row :gutter="8"><el-col :span="12">';
            var input_ = '<el-input @change="_restore" @keyup.enter.native="search" :on-icon-click="search" v-model="searchValue" placeholder="请输入您要搜索的内容" icon="search"></el-input>';
            if(typeof(opts.zidingyiTop) === 'string') {
                input_ = ''
            }
            el_.innerHTML = row + input_ + '</el-col></el-row></el-col><el-col :span="12"><el-row type="flex" justify="end">' + btnsString + "</div></el-row></el-col></el-row>" + tableString;
        }
        return table = new Vue({
            el: opts.el,
            data: function() {
                this.opts = opts;
                this.preParams = {};
                var self = this;
                var btns = this.opts.btns;
                for(var i = 0; i < btns.length; i++) {
                    (function(i) {
                        self[btns[i].authority] = function() {
                            btns[i].click.call(self);
                        }
                    })(i);
                }
                this._collectData = [];
                this._collectPageIndex = 1;
                this._collectNodataFlag = false;
                return {
                    currentPage: 1,
                    pageSize: this.opts.pageSize || 20, //默认每页20条
                    pageSizes: this.opts.pageSizes || [10], //下拉分页
                    total: 0,
                    tableData: [],
                    sels: [],
                    params: [],
                    searchValue: "",
                    searchTime:null,
                    height: this.opts.height || 500,
                    nodataFlag: false, //继续加载
                    hasResetPagination: false
                }
            },
            mounted: function() {
                this.params = {
                    scrollPageIndex: this.currentPage, //默认第一页
                    scrollPageSize: this.pageSize, //默认每页30条
                }
                var self = this,
                    isScrollToBottom_ = function() {
                        if(self.nodataFlag || self.hasResetPagination) {
                            return false;
                        }
                        isScrollToBottom(this, self.getData);
                    };
                self.$nextTick(function() {
                    var tablebody_ = self.$refs["table"].$el.getElementsByClassName("el-table__body-wrapper")[0];
                    if(opts.scrollPage) {
                        //滚动事件
                        tablebody_.onscroll = function(e) {
                            throttle(isScrollToBottom_, e);
                        }
                    }
                });
            },
            methods: {
                handleSizeChange: function(val) {
                    this.resetPagination();
                    this.params.scrollPageSize = val;
                    this.getData();
                },
                handleCurrentChange: function(val) {
                    this.resetPagination();
                    this.params.scrollPageIndex = val;
                    this.getData();
                },
                resetPagination: function() {
                    //this.searchValue = "";
                    rowsNum = 0;
                    this.sels = [];
                    this.tableData = [];
                    this.nodataFlag = false;
                    this.params.scrollPageIndex = 1;
                },
                //isNewGet,Boolean 是否为一个新的请求（true代表会重置请求参数）
                getData: function(params, isNewGet) {
                    if(isNewGet) {
                        this.resetPagination();
                    } else {
                        if(this.nodataFlag) {
                            console.log("已请求完所有数据");
                            return false;
                        }
                    }
                    if(params) {
                        params = extend_(this.params, params);
                        // 保存这一次的请求参数
                        this.preParams = {};
                        this.preParams = extend_(params, this.preParams);
                    } else {
                        this.preParams = extend_(this.params, this.preParams);
                    }
                    VanyAjax(this.opts.url, params || this.preParams, "GET", table.$el).done(function(data) {
                        /*返回的表格数据可能有其他有用的字段*/
                        for(var key in data) {
                            if(key !== "total" || key !== "rows") {
                                this["$" + key] = data[key];
                            }
                        }
                        if(data.total === 0) {
                            this.nodataFlag = true;
                            this.total = data.total;
                            return;
                        }
                        var totleCurrent = this.params.scrollPageSize * this.params.scrollPageIndex; //加载到当前页面时，应有的数据总数

                        if(totleCurrent >= data.total) {
                            this.nodataFlag = true;
                            //判断是否是滚动加载，滚动加载是续加，分页加载则是替换
                            if(this.opts.scrollPage) {
                                totleCurrent = data.total;
                            }
                            if(this.opts.pages) {
                                totleCurrent = data.total - this.params.scrollPageSize * (this.params.scrollPageIndex - 1); //替换当前页面时，应有的数据总数
                            }
                        }
                        var rows = data.rows;
                        for(var i = rowsNum; i < (this.opts.pages ?totleCurrent :this.params.scrollPageSize ); i++) {
                            this.tableData.push(rows[i]);
                        }
                        rowsNum = totleCurrent;
                        this.params.scrollPageIndex++;
                        if(this.searchValue === "") {
                            this._collectData = this._collectData.concat(rows);
                            this._collectPageIndex = this.params.scrollPageIndex;
                            this._collectNodataFlag = this.nodataFlag;
                        }
                        this.hasResetPagination = false;
                        this.total = data.total;
                        console.log(data.total);
                    }, false, this);
                },
                rowClick: function(row, event, column) {
                    if(this._rowClick) {
                        this._rowClick.call(this, row, event, column);
                    }
                },
                selectionChange: function(selection) {
                    this.sels=selection;
                },
                search: function() {
                    if(this._search) {
                        this.hasResetPagination = true;
                        this._search.call(this,this.searchValue,this.searchTime);
                    }
                },
                _restore: function(val) {
                    if(val === "") {
                        this.tableData = [].concat(this._collectData);
                        this.params.scrollPageIndex = this._collectPageIndex;
                        this.nodataFlag = this._collectNodataFlag;
                        this.preParams.searchValue = "";
                    }
                },
                on: function(type, fn) {
                    switch(type) {
                        case "search":
                            this._search = fn;
                            break;
                        case "rowClick":
                            this._rowClick=fn;
                    }
                }
            }
        });
    }
    window.VanyMyTable = VanyMyTable;
    /************************************************VanyTable结束************************************************/
})(window);
